<template>
    <div>
        <div class="n-layout-page-header">
            <n-card :bordered="false" title="部门管理">
                <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
                    <template #statusSlot="{ model, field }">
                        <n-input v-model:value="model[field]" />
                    </template>
                </BasicForm>
            </n-card>
        </div>
        <n-card :bordered="false" class="mt-4 proCard">
            <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" ref="actionRef"
                :actionColumn="actionColumn" @update:checked-row-keys="onCheckedRow" :bordered="false" :pagination="false">
                <template #tableTitle>
                    <n-button type="primary" :on-click="handleEdit.bind(null, {}, 1)">
                        <template #icon>
                            <n-icon>
                                <PlusOutlined />
                            </n-icon>
                        </template>
                        添加部门
                    </n-button>
                </template>
                <template #action>
                    <TableAction />
                </template>
            </BasicTable>
        </n-card>

        <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editTitle" style="border-radius: 8px;">
            <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120" class="py-4">
                <n-form-item label="部门名称" path="name">
                    <n-input maxlength="120" show-count :disabled="inputDisabled" placeholder="请输入部门名称"
                        v-model:value="fromValues.name" />
                </n-form-item>
                <n-form-item label="部门级别" path="level">
                    <n-input-number style="width: 100%;" placeholder="请输入部门级别" v-model:value="fromValues.level" />
                </n-form-item>
                <n-form-item label="部门排序" path="orderNum">
                    <n-input-number style="width: 100%;" placeholder="请输入部门级别" v-model:value="fromValues.orderNum" />
                </n-form-item>
                <n-form-item label="部门状态" path="deleted">
                    <n-select v-model:value="fromValues.deleted" placeholder="请选择部门状态"
                        :options="deletedOptions" />
                </n-form-item>
                <n-form-item label="部门简介" path="description">
                    <n-input maxlength="300" show-count type="textarea" :autosize="{
                        minRows: 3,
                        maxRows: 5
                    }" v-model:value="fromValues.description" filterable placeholder="请输入部门简介" />
                </n-form-item>
            </n-form>
            <div style="justify-content: end;display: flex;">
                <n-space>
                    <n-button ghost icon-placement="left" @click="handleCloseModel">
                        取消
                    </n-button>
                    <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
                </n-space>
            </div>
        </n-modal>
    </div>
</template>
  
<script lang="ts" setup>
import { ref, h, reactive } from 'vue';
import { useMessage, useDialog, type FormRules } from 'naive-ui';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { BasicTable, TableAction } from '@/components/Table';
import { columns } from './columns';
import { allDeptTree, saveDept, updateDept, removeDept } from '@/api/system/dept';
import { DeleteOutlined, EditOutlined, PlusOutlined } from '@vicons/antd';
import { ResultEnum } from '@/enums/httpEnum';
import { deletedOptions } from '@/utils/convert';
const message = useMessage();
const dialog = useDialog();
const formBtnLoading = ref(false);
const actionRef = ref();
const editTitle = ref('');
const isAdd = ref(1);
const showModal = ref(false);
const formRef: any = ref(null);
const inputDisabled = ref(false);
let fromValues = reactive({
    id: null,
    /** 父级ID */
    parentId: 0,
    /** 部门名称 */
    name: '',
    /** 部门级别 */
    level: 0,
    /** 部门排序 */
    orderNum: 0,
    /** 部门简介 */
    description: '',
    /** 部门状态 */
    deleted: 0,
});
const rules: FormRules = {
    level: {
        type: 'number',
        required: true,
        message: '请输入部门级别',
        trigger: ['blur', 'change'],
    },
    orderNum: {
        type: 'number',
        required: true,
        message: '请输入部门排序',
        trigger: ['blur', 'change'],
    },
    name: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入部门名称',
    },
    deleted: {
        type: 'number',
        required: true,
        trigger: ['blur', 'select'],
        message: '请选择状态',
    },
};
/**
 * 表格查询参数定义
 */
const schemas: FormSchema[] = [
    {
        field: 'name',
        component: 'NInput',
        label: '部门名称',
        componentProps: {
            placeholder: '请输入部门名称',
        },
    },
];
const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
});
const loadDataTable = async (res: any) => {
    return await allDeptTree({ ...getFieldsValue(), ...res });
};
const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
        return h(TableAction as any, {
            style: 'text',
            actions: createActions(record),
        });
    },
});

function createActions(record) {
    return [
        {
            label: '新增',
            type: 'success',
            icon: PlusOutlined,
            onClick: handleEdit.bind(null, record, 3),
            ifShow: () => {
                return true;
            },
            //auth: ['basic_list'],
        },
        {
            label: '编辑',
            type: 'primary',
            icon: EditOutlined,
            onClick: handleEdit.bind(null, record, 2),
            ifShow: () => {
                return true;
            },
            //auth: ['basic_list'],
        },
        {
            label: '删除',
            type: 'error',
            // 配置 color 会覆盖 type
            color: 'red',
            icon: DeleteOutlined,
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
                return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            //auth: ['basic_list'],
        },
    ];
}
function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
}

function reloadTable() {
    actionRef.value.reload();
}
/**
 * 查询
 */
function handleSubmit() {
    reloadTable();
}
/**
 * 重置查询
 */
function handleReset() {
    reloadTable();
}
/**
 * 新增，编辑，新增子节点
 * @param record 
 * @param addStatus 
 */
function handleEdit(record: Recordable, addStatus: number) {
    showModal.value = true;
    isAdd.value = addStatus;
    resetFrom();
    if (addStatus === 1) {
        editTitle.value = `新增部门`;
    }
    if (addStatus === 2) {
        editTitle.value = `编辑 ${record.name}`;
        fromValues = Object.assign(fromValues, record);
    }
    if (addStatus === 3) {
        editTitle.value = `新增 ${record.name}子节点`;
        fromValues = Object.assign(fromValues, { parentId: record.id });
    }
}
function resetFrom() {
    fromValues = Object.assign(fromValues, {
        id: null,
        /** 父级ID */
        parentId: 0,
        /** 部门名称 */
        name: '',
        /** 部门级别 */
        level: 0,
        /** 部门排序 */
        orderNum: 0,
        /** 部门简介 */
        description: '',
        /** 部门状态 */
        deleted: 0,
    });
}
/**
 * 新增编辑提交数据
 * @param e 
 */
function confirmForm(e: any) {
    e.preventDefault();
    formRef.value.validate(async (errors) => {
        if (!errors) {
            formBtnLoading.value = true;
            let data: any;
            if (isAdd.value === 2) {
                data = await updateDept(fromValues);
            } else {
                data = await saveDept(fromValues);
            }
            if (data.code !== ResultEnum.SUCCESS) {
                const resultMsg = data.data ? data.data : '';
                message.error(data.msg + '-' + resultMsg);
                formBtnLoading.value = false;
            }
            if (data.code === ResultEnum.SUCCESS) {
                message.success(data.msg);
                showModal.value = false;
                resetFrom();
                reloadTable();
            }
            formBtnLoading.value = false;
        } else {
            message.error('请填写完整信息');
        }
        formBtnLoading.value = false;
    });
}
/**
 * 新增编辑关闭model
 */
function handleCloseModel() {
    resetFrom();
    showModal.value = false;
}
/**
 * 删除确认
 * @param record 
 */
function handleDelete(record: Recordable) {
    dialog.warning({
        title: '警告',
        content: `确定删除${record.name}吗？`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: async () => {
            const data = await removeDept({ id: record.id });
            if (data.code !== ResultEnum.SUCCESS) {
                const resultMsg = data.data ? data.data : '';
                message.error(data.msg + '-' + resultMsg);
            }
            if (data.code === ResultEnum.SUCCESS) {
                message.success(data.msg);
                showModal.value = false;
                reloadTable();
            }
        },
    })
}
</script>
  
<style lang="less" scoped></style>
  